<template>
    <div class="app-container">
        <!--查询表单-->
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
                <el-input v-model="userQuery.name" placeholder="用户姓名"/>
            </el-form-item>

            <el-form-item>
                <el-select v-model="userQuery.sex" clearable placeholder="用户性别">
                    <el-option :value="1" label="男"/>
                    <el-option :value="2" label="女"/>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-input v-model="userQuery.address" placeholder="用户住址"/>
            </el-form-item>

            <el-form-item label="">
                <el-date-picker
                    v-model="createTimes"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="margin-right: 10px;width: 100%;"/>
            </el-form-item>

            <el-row style="display:flex">
                <el-button type="primary" icon="el-icon-search" @click="selectUsersByConditionPage()">查询</el-button>
                <el-button type="info" icon="el-icon-delete" @click="resetData()">清空</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="removeBatchByIds()">批量删除</el-button>
                <el-button type="success" icon="el-icon-plus" @click="add">添加</el-button>
            </el-row>
        </el-form>

        <!-- 列表 -->
        <el-table
            v-loading="listLoading"
            :data="list"
            stripe
            border
            style="width: 100%;margin-top: 10px;"
            fit
            highlight-current-row
            @selection-change="handleSelectionChange">

            <el-table-column type="selection"/>

            <el-table-column
                fixed
                label="序号"
                width="70"
                align="center">
                <template slot-scope="scope">
                {{ (page - 1) * limit + scope.$index + 1 }}
                </template>
            </el-table-column>

            <el-table-column prop="name" label="姓名" width="80"/>
            <el-table-column prop="age" label="年龄" width="80"/>
            <el-table-column label="性别" width="80">
                <template slot-scope="scope">
                    {{ scope.row.sex === 1 ? '男' : '女' }}
                </template>
            </el-table-column>
            <el-table-column prop="borrowBooks" label="所借图书" width="300"/>
            <el-table-column prop="address" label="住址" width="180"/>
            <el-table-column prop="createTime" label="创建时间" width="180"/>
            <el-table-column prop="updateTime" label="修改时间" width="180"/>

            <el-table-column fixed="right" label="操作" width="180" align="center">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row.id)" title="修改"/>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)" title="删除"/>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination
            :current-page="page"
            :total="total"
            :page-size="limit"
            :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
            style="padding: 30px 0; text-align: center;"
            layout="sizes, prev, pager, next, jumper, ->, total, slot"
            @current-change="selectUsersByConditionPage"
            @size-change="changeSize"/>

        <el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%" >
            <el-form ref="dataForm" :model="user" label-width="100px" size="small" style="padding-right: 40px;">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="user.name"/>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input-number v-model="user.age"/>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="user.sex" placeholder="请选择">
                        <el-option :value="1" label="男"/>
                        <el-option :value="2" label="女"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="所借图书" prop="borrowBooks">
                    <el-input v-model="user.borrowBooks" :rows="3" type="textarea"/>
                </el-form-item>
                <el-form-item label="住址" prop="address">
                    <el-input v-model="user.address" :rows="3" type="textarea"/>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false" size="small" icon="el-icon-refresh-right">取 消</el-button>
                <el-button type="primary" icon="el-icon-check" @click="saveOrUpdate()" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import user from '@/api/library/user'
import book from '@/api/library/book'

const defaultForm = {
  id: '',
  name: '',
  age: '',
  sex: '',
  borrowBooks: '',
  address: ''
}

export default {
    data() {
        return {
            listLoading: true, // 数据是否正在加载
            list: null, // banner列表
            total: 0, // 数据库中的总记录数
            page: 1, // 默认页码
            limit: 10, // 每页记录数
            userQuery: {}, // 查询表单对象
            createTimes: [],
            multipleSelection: [], //批量删除选中的记录列表
            dialogVisible: false,
            user: defaultForm,
            saveBtnDisabled: false,
            dialogRoleVisible: false
        }
    },

    //生命周期函数：内存准备完毕，页面尚未渲染
    created() {
        console.log('list created......')
        this.selectUsersByConditionPage()
    },

    //生命周期函数：内存准备完毕，页面渲染成功
    mounted() {
        console.log('list mounted......')
    },

    methods: {
        //当页码发生改变的时候
        changeSize(size) {
            console.log(size)
            this.limit = size
            this.selectUsersByConditionPage(1)
        },
        //条件查询用户，带分页
        selectUsersByConditionPage(page = 1) {
            this.page = page
            console.log('翻页。。。' + this.page)
            if (this.createTimes && this.createTimes.length == 2) {
                this.userQuery.createTimeBegin = this.createTimes[0]
                this.userQuery.createTimeEnd = this.createTimes[1]
            }
            user.selectUsersByConditionPage(this.page, this.limit, this.userQuery)
                .then(response => {
                    this.list = response.data.records
                    this.total = response.data.total
                    // 数据加载并绑定成功
                    this.listLoading = false
                })
        },
        //清空查询表单
        resetData() {
            this.userQuery = {}
            this.createTimes = []
            this.selectUsersByConditionPage()
        },
        //根据id逻辑删除用户
        removeUserById(id) {
            this.$confirm('此操作将永久删除用户记录，是否继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                return user.removeUserById(id)
            }).then(response => {
                this.$message.success(response.message || '删除成功')
                this.selectUsersByConditionPage(this.page)
            }).catch(() => {
                this.$message.info('取消删除')
            })
        },
        //批量删除用户
        removeBatchByIds() {
            if (this.multipleSelection.length === 0) {
                this.$message.warning('请选择要删除的记录！')
                return
            }
            this.$confirm('此操作将永久删除这些记录，是否继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                var ids = []
                this.multipleSelection.forEach(item => {
                    ids.push(item.id)
                })
                return user.removeBatchByIds(ids)
            }).then(response => {
                this.$message.success(response.message || '删除成功')
                this.selectUsersByConditionPage(this.page)
            })
        },
        //当多选选项发生变化时调用
        handleSelectionChange(selection) {
            console.log(selection)
            this.multipleSelection = selection
        },
        //点击添加按钮
        add() {
            this.dialogVisible = true //打开dialog对话框
            this.user = Object.assign({}, defaultForm)
        },
        //点击dialog对话框的确定按钮，判断是新增还是修改
        saveOrUpdate() {
            this.$refs.dataForm.validate(valid => {
                if (valid) {
                    this.saveBtnDisabled = true //防止表单重复提交
                    if (!this.user.id) { //记录中没有id，则是新增
                        this.insertUser()
                    } else { //有id，则是修改
                        this.modifyUser()
                    }
                }
            })
        },
        //新增用户
        insertUser() {
            user.insertUser(this.user)
                .then(response => {
                    this.$message.success('操作成功')
                    this.dialogVisible = false //关闭dialog对话框
                    this.selectUsersByConditionPage(this.page)
                })
        },
        //修改用户
        modifyUser() {
            user.modifyUser(this.user)
                .then(response => {
                    this.$message.success(response.message || '操作成功')
                    this.dialogVisible = false
                    this.selectUsersByConditionPage(this.page)
                })
        },
        //点击修改按钮，弹出dialog对话框，查询要修改的数据，进行回显
        edit(id) {
            this.user = {} //弹框之前，先把原对话框数据清空，避免花眼
            this.dialogVisible = true
            this.selectUserById(id)
        },
        //根据id查询用户
        selectUserById(id) {
            user.selectUserById(id)
                .then(response => {
                    this.user = response.data
                    console.log(this.user)
                })
        }
    }
}
</script>